define(["jquery","bbcare","comm/datatable/datatable","bld/app/comm/comm","bld/app/drug/drugList.servers","bld/app/drug/drugList.ui"],function($,$bb,$datatable,$bldcomm,$servers,$ui) {
    var drugList = {}, defaults = {};
        
    /**
     * 模态框小类回调函数
     */
    var modalSmallClass = function(data) {
        var smallClassId = $('#medicineSmallClass button.active').attr("id");
        $ui.smallClass({
            "id": "catalogId",
            "smallClass": data.medCatalogInfos,
            "smallClassId":smallClassId,
        });
    }

    /**
     * 模态框里的大类改变时触发
     */
    var onChangeBigClass = function(){
        var bigClassId = $(this).val();
        var params = {
            "medCatalogInfo":{ 
                "classId": bigClassId
            }
        };
        $servers.ajaxMedicineSmallClass(params,modalSmallClass);
    }

    /**
     * 选择搜索出的某一个药品
     */
    var selectMedicineName = function() {
        var datas = $(this).data("datas");
        $("#inputQuery").hide();
        var index = $(this).index();
        datas.medicines[index].status = "update";
        datas.medicines[index].resetFlag = true;
        modalUi(datas.className,datas.medicines[index]);
    }

    /**
     * 根据药品名称查询药品成功后的回调函数
     */
    var ajaxSelectCallBack = function(data,className) {
        if( data.rows.length > 0 ){
            $ui.selectCallBack({
                "id": "inputQuery",
                "list": data.rows
            });
            $("#inputQuery").show();
            $("#inputQuery .query_item").unbind("click");
            $("#inputQuery .query_item").data("datas",{"className":className,"medicines":data.rows});
            $("#inputQuery .query_item").click(selectMedicineName);
        }else{
            $("#inputQuery").hide();
        }
    }

    /**
     * 模态框内的药名搜索
     */
    var onSelectByName = function() {
        var className = $(this).data("className");
        var medicineName = $("#medicineName").val();
        var params = {
            "medicineName": medicineName
        };
        $servers.ajaxSelect(params,ajaxSelectCallBack,className);
    }

    /**
     * 添加成功后的回调函数
     */
    var ajaxAddCallBack = function(data,datas) {
        $('.' + datas.className).modal('hide');
        var index = $servers.getIndexByClassId(defaults.bigClass,datas.bigClassId);
        $('#medicineBigClass .btn-group button').eq(index).data("smallClassId",datas.smallClassId);
        $('#medicineBigClass .btn-group button').eq(index).click();
    }

    /**
     * 添加药品
     */
    var onAdd = function() {
        var medicineName = $.trim($("#medicineName").val());
        var classId = $("#classId").val();
        var catalogId = $("#catalogId").val();
        var frequencyDay = parseInt($("#frequencyDay").val());
        var frequencyTime = parseInt($("#frequencyTime").val());
        var calcuMethod = $("#calcuMethod").val();
        var medicineDose = parseFloat($("#medicineDose").val());
        var medUnitId = $("#medUnitId").val();
        var medicineType = $("#medicineType").val();
        var character = $("#character").val();
        var indication = $("#indication").val();
        var adverseReaction = $("#adverseReaction").val();
        var taboo = $("#taboo").val();
        var considerations = $("#considerations").val();
        var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
        var channelId = $bb.getChannelId();
        var obj = {"medicineName":medicineName,"frequencyDay":frequencyDay,"frequencyTime":frequencyTime,"medicineDose":medicineDose};
        if( $bldcomm.validateMedicine(obj) ){
            var params = {
                "oprInfo":{
                    "opCode": "2045",
                    "opType": "3",
                    "opNote": "【" + doctorName + "】医生添加药品【" + medicineName + "】",
                    "channelType": "2",
                    "channelId": channelId
                },
                "medicineInfo":{
                    "medicineName": medicineName,
                    "classId": classId,
                    "catalogId": catalogId
                },
                "medSkuInfo":{
                    "medicineDose": parseFloat(medicineDose),
                    "calcuMethod": calcuMethod,
                    "frequencyDay": parseInt(frequencyDay),
                    "frequencyTime": parseInt(frequencyTime),
                    "useUnitId": medUnitId, // 服用剂量单位 使用药物剂量单位
                    "medUnitId": medUnitId,
                    "medicineType": medicineType,
                    "character": character,
                    "indication": indication,
                    "adverseReaction": adverseReaction,
                    "taboo": taboo,
                    "considerations": considerations
                }
            };
            var datas = {
                "className":$(this).data("className"),
                "bigClassId":classId,
                "smallClassId":catalogId,
            };
            $servers.ajaxAdd(params,ajaxAddCallBack,datas);
        }
    }

    /**
     * 重置
     */
    var onReset = function(){
        var className = $(this).data("className");
        var obj = {};
        obj.class_id = $('#medicineBigClass button.active').attr("id");
        obj.parentId = $('#medicineSmallClass button.active').attr("id");
        obj.status = "add";
        modalUi(className,obj);
    }

    /**
     * 模态框初始化
     */
    var modalUi = function(className,obj){
        var options = {
            "dom": $("." + className + " .modal-body"),
            "bigClass":defaults.bigClass,
            "smallClass":defaults.smallClass,
            "units":defaults.units
        };
        $.extend(options,obj);
        $ui.add(options);
        $("." + className).modal("show");
        // 大类改变时触发
        $("#classId").unbind("change");
        $("#classId").change(onChangeBigClass);
        // 模态框内的药名搜索
        $("#medicineName").unbind("input propertychange");
        $("#medicineName").data("className",className);
        $("#medicineName").bind("input propertychange", onSelectByName);
        // 重置
        $("#reset").unbind("click");
        $("#reset").data("className",className);
        $("#reset").bind("click", onReset);
        // 添加药品
        $("#addSaveBtn").unbind("click");
        $("#addSaveBtn").data("className",className);
        $("#addSaveBtn").bind("click", onAdd);
        // 修改药品
        $("#update").unbind("click");
        $("#update").data("datas",{"className":className});
        $("#update").bind("click", $servers.onUpdate);
    }
       
    /**
     * 请求单位成功后的回调函数
     */
    var ajaxQueryUnit = function(data) {
        defaults.units = data.medUnits;
        var className = "drugListModal";
        $bb.modal({
            "className": className,
            "tit": "药品添加页",
        }, function() {
            var obj = {};
            obj.class_id = $('#medicineBigClass button.active').attr("id");
            obj.parentId = $('#medicineSmallClass button.active').attr("id");
            obj.status = "add";
            modalUi(className,obj);
        });
    }
        
    /**
     * 新增药品
     */
    var onAddClick = function() {
        $servers.ajaxQueryUnit({},ajaxQueryUnit);
    }

    /**
     * 选择小类
     */
    var onSmallClassSelect = function() {
        $(this).addClass('active').siblings('.active').removeClass('active');
        // 新增药品
        $("#addBtn").unbind("click");
        $("#addBtn").click(onAddClick);
        // 表格
        var id = $(".layout-bottom table").attr("id");
        $datatable.init({
            "id": id,
            "options": $servers.getOptions(defaults)
        });
        $datatable.table.api().ajax.reload();
    }

    /**
     * 添加小类成功后的回调函数
     */
    var ajaxInsertMedcatalog = function(data,datas) {
        $('.' + datas.className).modal('hide');
        var index = $('#medicineBigClass button.active').index();
        $('#medicineBigClass .btn-group button').eq(index).data("smallClassId",data.medCatalogId);
        $('#medicineBigClass .btn-group button').eq(index).click();
    }

    /**
     * 添加小类进行请求
     */
    var addSmallClass = function() {
        var catalogName = $('#catalogName').val();
        if (catalogName == '') {
            $('#catalogName').focus();
        }else{
            var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
            var channelId = $bb.getChannelId();
            var datas = $(this).data("datas");
            datas.bigClassId = $('#medicineBigClass button.active').attr('id');
            var params = {
                "oprInfo":{
                    "opCode": "2046",
                    "opType": "3",
                    "opNote": "【" + doctorName + "】医生新增药品树节点【" + catalogName + "】",
                    "channelType": "2",
                    "channelId": channelId
                },
                "medCatalogInfo":{
                    "catalogName": catalogName,
                    "classId": datas.bigClassId
                }
            };
            $servers.ajaxInsertMedcatalog(params,ajaxInsertMedcatalog,datas);
        }
    }

    /**
     * 添加药品小类事件
     */
    var onAddSmallClass = function() {
        var datas = {};
        datas.className = "drugListSmallClassModal";
        $bb.modal({
            "className": datas.className,
            "tit": "请输入药品小类名称",
        }, function() {
            $ui.addSmallClass({
                "dom": $("." + datas.className + " .modal-body"),
            });
            $("." + datas.className).modal("show");
            // 添加小类
            $("#add").unbind('click');
            $("#add").data("datas",datas);
            $("#add").click(addSmallClass);
        });
    }

    /**
     * 修改药品小类名称回调函数
     */
    var ajaxModifyMedcatalogInfo = function(data,smallClassId) {
        $bb.toastShow('修改成功');
        var index = $('#medicineBigClass button.active').index();
        $('#medicineBigClass .btn-group button').eq(index).data("smallClassId",smallClassId);
        $('#medicineBigClass .btn-group button').eq(index).click();
    }

    /**
     * 修改药品小类名称
     */
    var onModifyMedcatalogInfo = function() {
        $(this).prev().unbind('blur');
        var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
        var channelId = $bb.getChannelId();
        var catalogName = $(this).prev().val();
        var smallClassId = $(this).parent().attr('id');
        var params = {
            "oprInfo":{
                "opCode": "2078",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生修改药品目录小类【" + catalogName + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "medCatalogInfo":{
                "catalogName": catalogName,
                "id": smallClassId
            }
        };
        $servers.ajaxModifyMedcatalogInfo(params,ajaxModifyMedcatalogInfo,smallClassId);
    }

    /*删除药品小类回调函数 */
    var ajaxRemoveMedcatalogInfo = function(data) {
        $bb.toastShow('删除成功');
        var index = $('#medicineBigClass button.active').index();
        $('#medicineBigClass .btn-group button').eq(index).click();
    }

    /**
     * 请求删除药品小类事件
     */
    var confirmRemoveMedcatalogInfo = function(params){
        $servers.ajaxRemoveMedcatalogInfo(params,ajaxRemoveMedcatalogInfo);
    }

    /**
     * 删除药品小类事件
     */
    var onRemoveMedcatalogInfo = function() {
        $(this).prev().unbind('blur');
        var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
        var channelId = $bb.getChannelId();
        var catalogName = $(this).prev().val();
        var smallClassId = $(this).parent().attr('id');
        var params = {
            "oprInfo":{
                "opCode": "2079",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生删除药品目录小类【" + catalogName + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "medCatalogInfo":{
                "id": smallClassId
            }
        };
        $bb.toastConfirmShow(confirmRemoveMedcatalogInfo,params,"确认是否删除该药品小类？");
        
    }

    /*修改药品小类名称事件 */
    var onModifySmallClass = function(event) {
        event.stopPropagation();    //  阻止事件冒泡
        var target = $('#medicineSmallClass button.active');
        var html = target.html();
        if( html == '全部' ) return;
        var id = target.attr('id');
        if( target.children('input').length == 0 ){
            var element = '<input type="text"><i class="fa fa-pencil" aria-hidden="true"></i><i class="fa fa-times" aria-hidden="true"></i>';
            target.html(element).css('cursor', 'default').unbind('click');
            target.children("input").focus().val(html);
        }
        if( target.children('input').length > 0 ){
            $(window).click(function(e) {
                if ( !$(e.target).parent().hasClass('smallClass') && !$(e.target).hasClass('smallClass')) {
                    target.html(html);
                    target.click(onSmallClassSelect);
                }
            });
            // 修改小类名称
            target.children('.fa-pencil').unbind('click');
            target.children('.fa-pencil').click(onModifyMedcatalogInfo);
            // 删除小类
            target.children('.fa-times').unbind('click');
            target.children('.fa-times').click(onRemoveMedcatalogInfo);
        }
    }
    
    /**
     * 请求小类成功后的回调函数
     */
    var ajaxMedicineSmallClass = function(data,smallClassId) {
        defaults.smallClass = data.medCatalogInfos;
        $ui.medicineSmallClass({
            "id": "medicineSmallClass",
            "list": data.medCatalogInfos
        });
        // 默认选种小类的全部
        $('#medicineSmallClass button').unbind('click');
        $('#medicineSmallClass button').click(onSmallClassSelect);
        var index = smallClassId ? $servers.getIndexByClassId(data.medCatalogInfos,smallClassId)+1 : 0;
        $('#medicineSmallClass button').eq(index).click();
        // 添加小类
        $('#addSmallClass').unbind('click');
        $('#addSmallClass').click(onAddSmallClass);
        // 修改小类
        $('#modifySmallClass').unbind('click');
        $('#modifySmallClass').click(onModifySmallClass);
    }

    /**
     * 选择一个大类
     */
    var onBigClassSelect = function() {
        var smallClassId = $(this).data("smallClassId");
        $(this).addClass('active').siblings('.active').removeClass('active');
        var bigClassId = $(this).attr('id');
        var params = {
            "medCatalogInfo":{ 
                "classId": bigClassId
            }
        };
        $servers.ajaxMedicineSmallClass(params,ajaxMedicineSmallClass,smallClassId);
    }

    /**
     * 请求大类成功后的回调函数
     */
    var ajaxMedicineBigClass = function(data){
        defaults.bigClass = data.data;
        $ui.medicineBigClass({
            "id": "medicineBigClass",
            "list": data.data
        });
        $('#medicineBigClass .btn-group button').click(onBigClassSelect);
        $('#medicineBigClass .btn-group button').eq(0).click();
    }

    drugList.init = function(){
        $servers.ajaxMedicineBigClass(ajaxMedicineBigClass);
    };

    return drugList;
});